package com.education.business.service;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.education.common.cache.CacheBean;
import com.education.common.util.ObjectUtils;
import com.education.model.dto.AdminUserSession;
import com.education.model.entity.SystemAdmin;
import com.education.model.request.PageParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * service 基类
 * @author 余一
 * @date 2021/9/17  16:07
 */
public abstract class BaseService<M extends BaseMapper<T>,T> extends CrudService<M,T>{

    @Autowired
    @Qualifier("redisCacheBean")
    protected CacheBean cacheBean;
    @Resource
    protected CacheBean ehcacheBean;
    @Autowired
    protected HttpServletRequest request;
    @Resource
    protected RedisTemplate redisTemplate;
    protected final Logger logger = LoggerFactory.getLogger(BaseService.class);


    /**
     * 更新shiro缓存中的用户信息，避免由于redis缓存导致获取用户信息不一致的问题
     * @param adminUserSession
     */
    public void updateShiroCacheUserInfo(AdminUserSession adminUserSession){
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();
        //realName 认证信息的key，对应的value就是认证的user对象
        String realName = principals.getRealmNames().iterator().next();
        SimplePrincipalCollection principalCollection = new SimplePrincipalCollection(adminUserSession, realName);
        //调用subject的runAs方法，把新的PrincipalCollection放到session里面
        subject.runAs(principalCollection);
    }

    /**
     * 获取管理员用户信息
     * @return
     */
    public AdminUserSession getAdminUserSession(){
        Subject subject = SecurityUtils.getSubject();
        AdminUserSession adminUserSession = (AdminUserSession) subject.getPrincipal();
        if (ObjectUtils.isNotEmpty(adminUserSession)) {
            return adminUserSession;
        }
        return null;
    }

    public SystemAdmin getSystemAdmin(){
        AdminUserSession adminUserSession = getAdminUserSession();
        SystemAdmin systemAdmin = adminUserSession.getSystemAdmin();
        if (ObjectUtils.isNotEmpty(systemAdmin)) {
            return systemAdmin;
        }
        return null;
    }

    public Integer getAdminUserId(){
        if (ObjectUtils.isNotEmpty(getSystemAdmin())) {
            return getSystemAdmin().getId();
        }
        return null;
    }

}
